package com.xbongbong.formula.qlexpress.operator.date;

import com.ql.util.express.Operator;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.PaasDateUtil;
import com.xbongbong.paas.toolbox.util.RegexUtil;
import com.xbongbong.pro.enums.errorcodes.BusinessRuleErrorCodeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @author 吴峰
 * @version v1.0
 * @date 2019/8/9 9:51
 * @since v1.0
 */
public class OperatorAddDay extends Operator {


    public OperatorAddDay(String name){
        this.name = name;
    }

    public OperatorAddDay(String aliasName, String aName, String errorInfo){
        this.aliasName = aliasName;
        this.name = aName;
        this.errorInfo = errorInfo;
    }

    /**
     * 语法：ADDDAY(date,days)
     * 说明： 将指定日期加/减指定天数，date为指定日期，days为指定天数，当为负数时在date上减去此天数
     * 例如：录入【项目开始时间】、【项目预计天数】，通过ADDDAY函数自动填入【项目预计完成时间】。
     * @param list
     * list[0] 指定日期
     * list[1] 指定天数
     */
    @Override
    public Object executeInner(Object[] list) throws XbbException {
        if (Objects.isNull(list) || list.length < Constant.LENGTH) {
            return null;
        }

        Boolean isNumber = RegexUtil.isNumber(list[1].toString());
        if (!isNumber) {
            throw new XbbException(BusinessRuleErrorCodeEnum.API_ERROR_261007);
        }
        if (list[0] == null || StringUtils.equals(list[0].toString(), Constant.ZERO_STRING)) {
            return null;
        }
        Long startTime = PaasDateUtil.getInt(list[0]);
        long day = Long.valueOf(list[1].toString()) * (24*3600);
        return betweenDays(startTime, day);
    }

    /**
     * 计算两个时间 相差天数
     * @param beforeDay
     * @param lastDay
     * @return
     */
    private static long betweenDays(long beforeDay, long lastDay) {
        long day = lastDay + beforeDay;
        return day;
    }
}
